package com.tobeface.wechat.request.api;

import com.google.common.base.Objects;
import com.google.common.collect.ImmutableMap;
import com.tobeface.modules.lang.Requires;
import com.tobeface.wechat.request.AbstractWeChatApiRequestBuilder;
import com.tobeface.wechat.request.WeChatRequest;

import java.util.Map;

/**
 * @author loudyn
 */
public class QRApiRequestBuilder {

    public static final QRApiRequestBuilder INSTANCE = new QRApiRequestBuilder();

    /**
     * @return
     */
    public CreateQRApiRequestBuilder create() {
        return new CreateQRApiRequestBuilder();
    }

    public QRApiRequestBuilder() {
    }

    /**
     * @author loudyn
     */
    public class CreateQRApiRequestBuilder extends AbstractWeChatApiRequestBuilder {

        private String name;
        private int sceneId;
        private int expiredSeconds = 1800;

        /**
         *
         */
        CreateQRApiRequestBuilder() {
            super("https://api.weixin.qq.com/cgi-bin/qrcode/create", WeChatRequest.Verb.POST);
        }

        /**
         * @return
         */
        public CreateQRApiRequestBuilder tempScene() {
            this.name = "QR_SCENE";
            return this;
        }

        public CreateQRApiRequestBuilder expiredAfter(int seconds) {
            Requires.isTrue(seconds > 0 && seconds <= 1800);
            this.expiredSeconds = seconds;
            return this;

        }

        /**
         * @return
         */
        public CreateQRApiRequestBuilder limitScene() {
            this.name = "QR_LIMIT_SCENE";
            return this;
        }

        /**
         * @param sceneId
         * @return
         */
        public CreateQRApiRequestBuilder sceneId(int sceneId) {
            Requires.isTrue(sceneId > 0, "sceneId must gt 0!");
            this.sceneId = sceneId;
            return this;
        }

        @Override
        protected void configRequest(WeChatRequest request) {

            Map<String, Object> sceneIdInfo = ImmutableMap.<String, Object>of(
                    "scene_id", sceneId
            );
            Map<String, Object> actionInfo = ImmutableMap.<String, Object>of(
                    "action_info", ImmutableMap.of("scene", sceneIdInfo)
            );
            Map<String, Object> entityInfo = ImmutableMap.<String, Object>of(
                    "action_name", name
            );

            if (!isTempScene()) {
                request.entity(entityInfo);
                return;
            }

            request.entity(ImmutableMap.builder().putAll(entityInfo).put("expire_seconds", expiredSeconds).build());
        }

        private boolean isTempScene() {
            return Objects.equal("QR_SCENE", name);
        }
    }

}
